package com.bdqn.controller;


import com.alibaba.fastjson.JSON;
import com.bdqn.common.Constants;
import com.bdqn.pojo.Account;
import com.bdqn.pojo.BookOrder;
import com.bdqn.pojo.ReserveOrder;
import com.bdqn.pojo.RoomType;
import com.bdqn.service.AccountService;
import com.bdqn.service.BookOrderService;
import com.bdqn.service.ReserveOrderService;
import com.bdqn.service.RoomTypeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 前台用户控制器
 *
 * @author Administrator
 */
@Slf4j
@RequestMapping("/home/account")
@Controller
public class HomeAccountController {

    @Resource
    private ReserveOrderService reserveOrderService;

    @Resource
    private RoomTypeService roomTypeService;
    @Resource
    private AccountService accountService;


    @Resource
    BookOrderService bookOrderService;

    /**
     * 前台用户中心首页
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView list(ModelAndView model, HttpServletRequest request) {
        Account account = (Account) request.getSession().getAttribute("account");
        System.out.println("**********************+++"+account.getName());
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("accountId", account.getId());
        queryMap.put("offset", 0);
        queryMap.put("pageSize", 999);
        model.addObject("ReserveOrderList", reserveOrderService.findList(queryMap));
        model.addObject("roomTypeList", roomTypeService.findAll());
        model.setViewName("/grzx/index");
        return model;
    }

    //删除
    @RequestMapping("/del")
    public String room(Model model, Long id ){
        System.out.println("*********"+id);
        int aa=bookOrderService.del(id);
        return "redirect:/home/account/index";
    }




    @RequestMapping("/select")
    public String select(Model model,HttpServletRequest request){
        Account account = (Account) request.getSession().getAttribute("account");
        model.addAttribute("accountAll",accountService.account( account.getId()));
       return "grzx/settings";
    }

    @RequestMapping("/update")
    public String update(Model model, Account account, HttpServletRequest request, HttpSession session,@RequestParam(value = "a_logoPicPath",required =false)MultipartFile a_logoPicPath) {
        // 定义文件存放目录
        String uploadPath = request.getSession().getServletContext().getRealPath(Constants.UPLOAD_PATH);
        // 从上传的文件列表中获得第1个文件
        // MultipartFile idPic = attachs[0]; // 获得上传的证件照图片
        // 证件照图片文件上传，成功后返回地址
        Map<String,String> map=multipartFileUpload(uploadPath, request, a_logoPicPath);
        String idPicPath=map.get("uploadFilePath"); // 调用文件上传方法，成功则返回上传地址
        if(idPicPath==null){
            String uploadFileError = (String) request.getAttribute("uploadFileError");
            request.setAttribute("idPicUploadError", uploadFileError);
            request.removeAttribute("uploadFileError"); // 临时使用，使用完毕后移除信息
            return "grzx/update";
        }else {
//            //上传图图片
//            appInfo.setLogoPicPath(idPicPath);//相对位置
//            appInfo.setLogoLocPath(uploadPath+"\\"+map.get("fileName"));//绝对位置
            account.setImg(uploadPath+"\\"+map.get("fileName"));
        }
        System.out.println("*********" + account.toString());
        int number = accountService.edit(account);
            if(number>0){
                return "redirect:/home/account/select";
            }else{
                return "redirect:/home/account/show";
            }


    }



    /**
     * 多部件文件上传（错误信息临时保存在request作用域uploadFileError属性中）
     *
     * @return 成功返回文件上传地址，返回null表示文件上传失败
     */
    public Map<String,String> multipartFileUpload(String uploadPath, HttpServletRequest request, MultipartFile multipartFile) {
        String uploadFilePath = null; // 文件上传地址，返回null表示文件上传失败
        Map<String,String> map = new HashMap<String, String>();
        map.put("uploadFilePath",uploadFilePath);
        // 定义文件存放目录

        System.out.println("上传文件路径：" + uploadPath);

        if (!multipartFile.isEmpty()) {
            // 获取上传的文件信息
            String originalFile = multipartFile.getOriginalFilename(); // 原文件名称
            System.out.println("原文件名称为：" + originalFile);
            String prefix = FilenameUtils.getExtension(originalFile); // 原文件后缀

            System.out.println("原文件后缀为：" + prefix);
            long fileSize = multipartFile.getSize(); // 原文件大小
            System.out.println("上传文件大小：" + fileSize);

            // 判断上传的文件是否符合要求
            if (fileSize > Constants.MAX_FILE_SIZE) { // 上传文件大小不能超过500KB
                request.setAttribute("uploadFileError", " * 上传文件大小不得超过 500KB");
                return map;
            }
            if (!(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("pneg"))) {
                request.setAttribute("uploadFileError", " * 上传文件格式只能是jpg、jpeg、png、pneg");
                return map;
            }

            // 确定文件存储名称
            String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000) + "_Personal." + prefix;

            System.out.println("新生成的文件名为：" + fileName);

            map.put("fileName",fileName);
            // 将上传的文件保存到目标位置
            File targetFile = new File(uploadPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs(); // 如果目录不存在则生成目录
            }
            // 保存文件
            try {
                // 存储物理地址 + 生成的文件名称
                multipartFile.transferTo(new File(targetFile, fileName));
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("uploadFileError", " * 文件上传失败！");
                return map;
            }
            // 文件上传完成就可以拿到地址
            uploadFilePath =  Constants.UPLOAD_PATH + File.separator + fileName;
        }
        map.put("uploadFilePath",uploadFilePath);

        // 返回文件上传成功后的地址，失败时返回null，并且将失败信息记录到
        return map;
    }
    @RequestMapping("/show")
    public String show(Model model,HttpServletRequest request){
        Account account = (Account) request.getSession().getAttribute("account");
        model.addAttribute("accountAll",accountService.account( account.getId()));
        return "grzx/update";
    }

    @PostMapping(value = "/rooms")
    @ResponseBody
    public String ReserveOrderAct(Model model,ReserveOrder reserveOrder,RoomType roomType, HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("reserveOrder",reserveOrder);
        session.setAttribute("roomType",roomType);
        log.info("1111"+roomType.getName());


        RoomType roomType1 = (RoomType) session.getAttribute("roomType");
        System.out.println("12123123"+roomType1.getName());
        Map<String, String> ret = new HashMap<String, String>();
        if (reserveOrder == null){
            ret.put("type", "error");
            ret.put("msg", "请填写正确的预定订单信息!");
            return JSON.toJSONString(ret);
        }
        Account account =(Account) request.getSession().getAttribute("account");
        if (account == null) {
            ret.put("type", "error");
            ret.put("msg", "你还未登陆哦!");
            return JSON.toJSONString(ret);
        }
        reserveOrder.setAccountId(account.getId());
        if (reserveOrder.getRoomTypeId() == null) {
            ret.put("type", "error");
            ret.put("msg", "房型不能为空!");
            return JSON.toJSONString(ret);
        }
        if (StringUtils.isEmpty(reserveOrder.getName())) {
            ret.put("type", "error");
            ret.put("msg", "预定订单联系人名称不能为空!");
            return JSON.toJSONString(ret);
        }
        if (StringUtils.isEmpty(reserveOrder.getMobile())) {
            ret.put("type", "error");
            ret.put("msg", "预定订单联系人手机号不能为空!");
            return JSON.toJSONString(ret);
        }
        if (StringUtils.isEmpty(reserveOrder.getIdCard())) {
            ret.put("type", "error");
            ret.put("msg", "联系人身份证号不能为空!");
            return JSON.toJSONString(ret);
        }
        if (StringUtils.isEmpty(reserveOrder.getArriveDate())) {
            ret.put("type", "error");
            ret.put("msg", "到达时间不能为空!");
            return JSON.toJSONString(ret);
        }
        if (StringUtils.isEmpty(reserveOrder.getLeaveDate())) {
            ret.put("type", "error");
            ret.put("msg", "离店时间不能为空!");
            return JSON.toJSONString(ret);
        }
        reserveOrder.setPrice(roomType1.getPrice());
        reserveOrder.setCreateTime(new Date());
        reserveOrder.setStatus(0);
        if (reserveOrderService.add(reserveOrder) <= 0) {
            ret.put("type", "error");
            ret.put("msg", "添加失败，请联系管理员!");
            return JSON.toJSONString(ret);
        }
        roomType = roomTypeService.find(reserveOrder.getRoomTypeId());
        // 预定成功后去修改该房型的预定数
        if (roomType != null) {
            roomType.setBookNum(roomType.getBookNum() + 1);
            roomType.setAvilableNum(roomType.getAvilableNum() - 1);
            roomTypeService.updateNum(roomType);
            // 如果可用的房间数为0，则设置该房型状态已满
            if (roomType.getAvilableNum() == 1) {
                roomType.setStatus(1);
                roomTypeService.edit(roomType);
            }
        }
        System.out.println("122222111111");
        ret.put("type", "success");
        ret.put("msg", "入住成功!");

        return JSON.toJSONString(ret);
    }

    @RequestMapping("/upd")
    public String upd(Model model, Long id ){
        System.out.println("*********"+id);
        int aa=bookOrderService.upd(id);
        return "redirect:/home/account/index";
    }
    /**
     * 支付房间页面
     *
     * @param model
     * @return
     */
//    @RequestMapping(value = "/room")
//    public ModelAndView ReserveOrder(ModelAndView model, Long roomTypeId) {
//        model.addObject("roomType", roomTypeService.find(roomTypeId));
//        model.setViewName("redirect:/home/account/room");
//        return model;
//    }
}
